package com.zk.algorithm.math;

import com.zk.algorithm.Utils;
import com.zk.algorithm.annotation.LeetCodeExplore;
import com.zk.algorithm.annotation.Medium;

import java.util.HashSet;
import java.util.Set;

@Medium
@LeetCodeExplore
public class HappyNumber {

    public static void main(String...args) {
        Utils.println(new HappyNumber().isHappy(1));
    }

    public boolean isHappy(int n) {
        Set<Integer> duplicate = new HashSet<>();
        duplicate.add(n);

        while (n != 1) {
            n = calcPowerOfAllDigits(n);

            if (!duplicate.add(n)) {
                return false;
            }
        }

        return true;
    }

    public int calcPowerOfAllDigits(int n) {
        int result = 0;

        while (n > 0) {
            int carry = n % 10;
            result += carry * carry;
            n = n / 10;
        }

        return result;
    }

}
